import Vue from 'vue';
import getCommand from './getCommand';
import form from './form';

/**
 * 表单加载数据和保存数据通用流程
 */
export default {
  mixins: [
    getCommand,
    form,
  ],

  data() {
    return {
      gridLayout: 'total, sizes, prev, pager, next, jumper',
      tableHeight: '529px',
      gridPageSize: [10, 20, 50, 100, 200, 500],
      sendingData: undefined,
      option: undefined,
      summariesText: '所有页汇总',
      localSummariesText: '当前页汇总',
      prevCursorList: [],
    };
  },
  computed: {
    cTableData() {
      return {
        ...this.tableData,
        list: _.slice(this.tableData.list, (this.filters.page - 1) * this.filters.size, this.filters.page * this.filters.size),
      };
    },
  },

  watch: {
    // time: {
    //   handler(time) {
    //     this.$nextTick(() => {
    //       if (time) {
    //         this.filters.date = _.toTimestamp(_.find(this.periods || consts.TIME_PERIOD, {value: time}));
    //         this.getAll();
    //       }
    //
    //     });
    //   },
    //   immediate: true
    // }
  },

  methods: {
    sortChange(data) {
      const { order, column } = data;

      if (order) {
        if (column.property) {
          this.filters.order = column.property;
          if (order === 'ascending') {
            this.filters.sort = 'asc';
          } else {
            this.filters.sort = 'desc';
          }
          this.gridSearch();
        } else {
          throw new Error('没有找到排序用property');
        }
      } else {
        this.filters.sort = undefined;
        this.filters.order = undefined;
        this.gridSearch();
      }
    },

    gridSearch() {
      this.filters.page = 1;
      this.prevCursorList = [];
      if (this.filters.cursor) {
        this.filters.cursor = undefined;
      }
      this.doGet({ action: 'getGrid' });
    },

    submitFilterForm(formInline) {
      this.getFilterData(formInline);
      this.gridSearch();
    },

    exportFilterForm(formInline) {
      this.getFilterData(formInline);
      this.exportHandle();
    },

    getFilterData(formInline) {
      const { time } = formInline;
      let startTime;
      let endTime;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startTime = time[0];
        endTime = time[1];
        formInline = { ...formInline, startTime, endTime };
      } else {
        this.filters.startTime = undefined;
        this.filters.endTime = undefined;
      }
      this.filters = { ...this.filters, ...formInline };
    },
    gridSizeChange(val) {
      this.filters.size = val;
      this.doGet({ action: 'getGrid' });
    },

    gridCurrentChange(val) {
      this.filters.page = val;
      this.doGet({ action: 'getGrid' });
    },

    localGridSizeChange(val) {
      this.filters.size = val;
    },

    localGridCurrentChange(val) {
      this.filters.page = val;
    },

    cursorGridSizeChange(val) {
      this.filters.size = val;

      this.gridSearch();
    },

    cursorPrevClickChange(val) {
      this.filters.page = val;
      this.filters.cursor = this.prevCursorList.pop();
      this.doGet({ action: 'getGrid' });
    },

    cursorNextClickChange(val) {
      if (this.filters.page > 1) {
        this.prevCursorList.push(this.filters.cursor);
      }

      this.filters.page = val;

      this.filters.cursor = this[this.sendingData || 'tableData'].cursor;
      this.doGet({ action: 'getGrid' });
    },

    getLocalSummaries({ columns, data }) {
      const fStatistic = [];
      _.each(columns, (column, index) => {
        if (column.property) {
          fStatistic[index] = _.sumBy(data, o => Number(o[column.property] ? o[column.property] : 0) * 100, // 避免js浮点数相加时出现的bug
          );
          fStatistic[index] = fStatistic[index] / 100;
          if (_.isNumber(fStatistic[index]) && !_.isNaN(fStatistic[index])) {
            const columnStatistic = _.find(this.statistic, { index });

            if (columnStatistic) {
              if (columnStatistic.localFormat) {
                fStatistic[index] = columnStatistic.localFormat(fStatistic[index]);
              } else if (columnStatistic.format) {
                fStatistic[index] = columnStatistic.format(fStatistic[index]);
              }
            } else {
              fStatistic[index] = fStatistic[index];
            }
          } else {
            fStatistic[index] = undefined;
          }
        }
      });

      fStatistic[0] = this.localSummariesText;
      return fStatistic;
    },

    getSummaries() {
      const fStatistic = [];
      _.each(this.statistic, (statisticInfo) => {
        fStatistic[statisticInfo.index] = statisticInfo.format
          ? statisticInfo.format(_.result(this, statisticInfo.prop)) : _.result(this, statisticInfo.prop);
      });
      if (!fStatistic[0]) {
        fStatistic[0] = this.summariesText;
      }

      return fStatistic;
    },
    exportExcel({ action = 'getGrid' }) {
      Vue.set(this.filters, 'exportExcel', true);
      this.doGet({ action });
      // 由于页面无限刷新问题，nextTick 触发提前，待优化
      setTimeout(() => {
        Vue.set(this.filters, 'exportExcel', false);
      }, 1000);
      // this.$nextTick(() => {
      //   Vue.set(this.filters, 'exportExcel', false);
      // });
    },
    downLoadExcel({ action = 'getGrid' }){
      this.doGet({ action });
      this.$store.dispatch(types.GET_DOWNLOAD_LIST);
      this.$store.commit(types.DOWNLOAD_LIST_VISIBLE,true);
    },
  },
  mounted() {
    // 设置默认查询时间为当天
    if (this.filterDateType) {
      this.filters = {
        ...this.filters,
        startTime: moment().format('YYYY-MM-DD 00:00:00'),
        endTime: moment().format('YYYY-MM-DD 23:59:59'),
      };
    }
  },
};


// import getCommand from './getCommand';
// import form from './form';
// import Sortable from 'sortablejs'

// /**
//  * 表单加载数据和保存数据通用流程
//  */
// export default {
//   mixins: [
//     getCommand,
//     form
//   ],

//   data() {
//     return {
//       gridPageSize: [10, 20, 30, 50],
//       gridLayout: 'total, sizes, prev, pager, next, jumper',
//       tableSortAble: false,
//       sortable:null,
//       sendingData: undefined,
//       option: undefined,
//       filterDateType: true,
//     }
//   },
//   watch: {
//     // filters:{
//     //   handler:(val,oldVal)=>{
//     //     console.log(val,oldVal)
//     //   },
//     //   // 深度观察
//     //   deep:true
//     // },

//     newList(data){
//       if(data.length !== 0 && !_.isEqual(data,this.oldList.slice())){
//         this.doSave({action: 'saveSort',type:'save'});
//       }
//     },
//     tableSortAble(data){
//       if(data){
//         this.setSort()
//       }else{
//         this.sortable.destroy()
//       }
//     }
//   },

//   computed:{
//     tableList(){
//       let list =[]
//       if(!_.isUndefined(this.sendingData)){
//         list = _.result(this,this.sendingData)

//         // 判断filters是否有传参数
//         const filterNow = _.some(this.filters,o=>!_.isEmpty(o))
//         if(filterNow){
//           this.tableSortAble = false
//         }
//       }
//       return list
//     },
//     oldList(){
//       if(this.tableSortAble && this.tableList && this.tableList.length>0){
//         return this.tableList.map(o=>o[this.option])
//       }
//       return []
//     },
//     newList(){
//       if(this.tableSortAble && this.tableList &&  this.tableList.length>0){
//         return this.oldList.slice()
//       }
//       return []
//     },
//   },
//   methods: {
//     gridSearch() {
//       this.filters.page = 1;
//       this.doGet({action: 'getGrid'});
//     },
//     gridSizeChange(val) {
//       this.filters.size = val;
//       this.doGet({action: 'getGrid'});
//     },
//     gridCurrentChange(val) {
//       this.filters.page = val;
//       this.doGet({action: 'getGrid'});
//     },
//     setSort() {
//       const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
//       this.sortable = Sortable.create(el, {
//         ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
//         setData: function (dataTransfer) {
//           dataTransfer.setData('Text', '')
//           // to avoid Firefox bug
//           // Detail see : https://github.com/RubaXa/Sortable/issues/1012
//         },
//         onEnd: evt => {
//           const list = this.tableList
//           const targetRow = list.splice(evt.oldIndex, 1)[0]
//           list.splice(evt.newIndex, 0, targetRow)

//           // for show the changes, you can delete in you code
//           const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
//           this.newList.splice(evt.newIndex, 0, tempIndex)
//         }
//       })
//     },
//     submitFilterForm(formInline) {
//       const {time} = formInline;
//       let startTime= undefined, endTime= undefined;
//       if(!_.isUndefined(time) && _.isArray(time)){
//         startTime= time[0];
//         endTime= time[1];
//         formInline = {...formInline,startTime,endTime}
//       }else{
//         this.filters.startTime = undefined;
//         this.filters.endTime = undefined;
//       }
//       this.filters = {...this.filters,...formInline}
//       this.gridSearch();
//     },
//     initSort(api, sortAble, sendingData, option) {
//       this.tableSortAble = sortAble;
//       this.option = option
//       this.sendingData = sendingData
//       this.bindSave(api, 'saveSort', 'newList', {

//       });
//     },
//   },
//   mounted(){
//     // 设置默认查询时间为当天
//     if(this.filterDateType){
//       this.filters = {
//         ...this.filters,
//         startTime:moment().format('YYYY-MM-DD 00:00:00'),
//         endTime:moment().format('YYYY-MM-DD 23:59:59'),
//       }
//     }
//   }
// };
